﻿@model Nop.Admin.Models.Logistics.MapContextModel

<div>
    <script type="text/javascript" src="https://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0&s=1"></script>
    <script type="text/javascript">

        //
        // Common functions
        //
        var map = null; // The map object used to invoke Bing APIs.

        var directionsManager = null;
        var directionsErrorEventObj = null;
        var directionsUpdatedEventObj = null;

        var searchManager = null;
        var locationinfos = new Array(); // Selected location information stored in an Array
        var processedLocations = new Array(); // All valid geo locations
        var errorLocationIds = new Array();

        var currentProcessingLoc = 0;
        var globalmaxorder = 0;
        var matchLoc = new Array();
        var matchCord = {};
        var hasMatch;

        var defaultarray = [];
        var a = 0;
        $('#planning-table input[type="text"]').each(function () {
            if ($(this).val != '') {
                defaultarray.push({ key: a, value: $(this).val() });
                $(this).attr("data-defaultorder", a);
                a++;
            }
        });


        function getMap() {
            
            @if (Model.SequentialLocations != null && Model.SequentialLocations.Count > 0)
            {
            <text>var info;</text>
                foreach (var li in Model.SequentialLocations)
                {
                <text>
                    info = { id: "@li.Id", address: "@li.Address", addressId: "@li.AddressId", packageId: "@li.PackageId", type: "@li.Attribute", status: "@li.Status" }
                    hasMatch = false;
                    if (!$.isEmptyObject(matchLoc)) {
                        for (var m in matchLoc) {
                            if ("addressId" in matchLoc[m] && matchLoc[m].addressId == "@li.AddressId") {
                                matchLoc[m].list.push(info);
                                hasMatch = true;
                            }
                        }
                    }
                    if (!hasMatch) {
                        matchLoc.push({ addressId: "@li.AddressId", list: [info] });
                        locationinfos.push(info);
                    }
                </text>
                }
            }
            
            // Initialze map object.
            map = new Microsoft.Maps.Map(document.getElementById('logisticsMap'), { credentials: '@Model.MapApiKey' });
            // Removes focus from the map control so that it does not respond to keyboard events.
            map.blur();

            showMsg("Searching locations...");

            startSearchLocations();
        }

        function showMsg(message) {
            var msg = document.getElementById('mapErrors').innerHTML;
            document.getElementById('mapErrors').innerHTML = msg + message + "<br />";
        }

        function showMap() {
            map.entities.clear();
            
            for (var m in matchLoc) {
                if ("location" in matchLoc[m]) {
                    var latLngString = matchLoc[m].location.latitude + "_" + matchLoc[m].location.longitude;
                    if (!(latLngString in matchCord)) {
                        matchCord[latLngString] = {
                            list: matchLoc[m].list,
                            loc: matchLoc[m].location,
                            address: matchLoc[m].formattedAddress
                        }
                    } else {
                        matchCord[latLngString].list = matchCord[latLngString].list.concat(matchLoc[m].list);
                    }
                }
            }
            
            @if (@Model.ShowRoute)
            {
                <text>
            showMsg("Caculating route...");
            showDirections();
            </text>
            } else {
                <text>
                    showMsg("Displaying map markers.");
                </text>
            }

            pushPin();

            var bestview = Microsoft.Maps.LocationRect.fromLocations(processedLocations);
            map.setView({ bounds: bestview, zoom: 12 });
        }

        //
        // Search locations
        //
        function createSearchManager() {
            if (searchManager == null) {
                map.addComponent('searchManager', new Microsoft.Maps.Search.SearchManager(map));
                searchManager = map.getComponent('searchManager');
            }
        }

        function startSearchLocations() {
            Microsoft.Maps.loadModule('Microsoft.Maps.Search', { callback: geocodeRequest })
        }

        function geocodeRequest() {
            createSearchManager();

            doSearch();
        }

        function doSearch() {
            if (currentProcessingLoc < locationinfos.length) {
                var request = {
                    where: locationinfos[currentProcessingLoc].address,
                    count: 1,
                    bounds: map.getBounds(),
                    callback: onGeocodeSuccess,
                    errorCallback: onGeocodeFailed,
                    userData: null
                };
                searchManager.geocode(request);
            }
        }

        function onGeocodeSuccess(result, userData) {
            if (result) {
                var topResult = result.results && result.results[0];
                if (topResult) {
                    locationinfos[currentProcessingLoc].geo = topResult.location;
                    processedLocations.push(topResult.location);
                    for (var m in matchLoc) {
                        if (matchLoc[m].addressId == locationinfos[currentProcessingLoc].addressId) {
                            matchLoc[m].location = topResult.location;
                            matchLoc[m].formattedAddress = result.results[0].name;
                        }
                    }
                }
                else {
                    handleGeoError(locationinfos[currentProcessingLoc])
                }
            }
            else {
                handleGeoError(locationinfos[currentProcessingLoc])
            }

            currentProcessingLoc++;
            if (currentProcessingLoc < locationinfos.length) {
                doSearch();
            }
            else {
                showMap();
            }
        }

        function onGeocodeFailed(result, userData) {
            handleGeoError(locationinfos[currentProcessingLoc])

            currentProcessingLoc++;
            if (currentProcessingLoc < locationinfos.length) {
                doSearch();
            }
            else {
                showMap();
            }
        }

        function handleGeoError(info)
        {
            info.geo = null;
            errorLocationIds.push(currentProcessingLoc);
            showMsg('The address <a target="blank" href="@Url.Action("AddressEdit")?locationId=' + info.id + '&edit=true">' + info.address + '</a> cannot be found.');
            var packageid = info.packageId;
            var addresstype = info.type;
            var row = $('#planning-table tr.package-' + packageid);
            if (row.length) {
                if (addresstype == "PickUp") {
                    row.find('.item-pickupaddress').css("background", "red");
                } else if (addresstype == "Delivery") {
                    row.find('.item-destinationaddress').css("background", "red");
                }
            }
        }

        //
        // Draw directions/routes
        //
        function showDirections() {
            //if (!directionsManager) {
            //    Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: addWaypoint });
            //}
            //else {
            //    addWaypoint();
            //}

            Microsoft.Maps.registerModule("RouteServiceHelper", "/subsites/Administration/Scripts/RouteServiceHelper.min.js");
            Microsoft.Maps.loadModule("RouteServiceHelper", { callback: calculateRoute });
        }

        function calculateRoute() {
            //Create route options
            var options = {
                avoid: null,
                distanceBeforeFirstTurn: 0,
                heading: null,
                optimize: 'time',
                routePathOutput: 'Points',
                travelMode: 'Driving',
                distanceUnit: 'km',
                culture: null,
                batchSize: 24
            };

            RouteServiceHelper.GetRoute(processedLocations, '@Model.MapApiKey', options, onRouteFinished);
        }

        function onRouteFinished(result) {
            if (result && result.statusCode == 200 &&
                  result.resourceSets &&
                  result.resourceSets.length > 0 &&
                  result.resourceSets[0].resources &&
                  result.resourceSets[0].resources.length > 0) {

                showMsg("Caculating route done.");

                var res = result.resourceSets[0].resources[0];

                //Set map view based on bounding box
                map.setView({ bounds: Microsoft.Maps.LocationRect.fromEdges(res.bbox[2], res.bbox[1], res.bbox[0], res.bbox[3]), padding: 20 });

                //Draw route path
                if (res.routePath && res.routePath && res.routePath.line
                      && res.routePath.line.coordinates
                      && res.routePath.line.coordinates.length >= 2) {
                    var p = [],
                    c = res.routePath.line.coordinates;

                    for (var i = 0; i < c.length; i++) {
                        p.push(new Microsoft.Maps.Location(c[i][0], c[i][1]));
                    }

                    map.entities.push(new Microsoft.Maps.Polyline(p, { strokeColor: new Microsoft.Maps.Color(156, 0, 0, 255) }));
                }

                //Draw Waypoints
                //for (var i = 0; i < res.routeLegs.length; i++) {
                //    map.entities.push(new Microsoft.Maps.Pushpin(
                //        new Microsoft.Maps.Location(res.routeLegs[i].actualStart.coordinates[0], res.routeLegs[i].actualStart.coordinates[1]), {
                //            text: i + 1 + ''
                //        }));
                //}

                //map.entities.push(new Microsoft.Maps.Pushpin(
                //      new Microsoft.Maps.Location(res.routeLegs[res.routeLegs.length - 1].actualEnd.coordinates[0], res.routeLegs[res.routeLegs.length - 1].actualEnd.coordinates[1]), {
                //          text: res.routeLegs.length + 1 + ''
                //      }));
            } else if (result && result.statusCode != 200) {
                showMsg("Error: " + result.errorDetails);
            }
        }

        //function createDirectionsManager() {
        //    if (!directionsManager) {
        //        directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
        //    }

        //    directionsManager.resetDirections();

        //    directionsErrorEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError',
        //        function (arg) { alert(arg.message) });
        //    directionsUpdatedEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated',
        //        function () { });
        //}

        //function addWaypoint() {
        //    if (!directionsManager) {
        //        createDirectionsManager();
        //    }
        //    directionsManager.resetDirections();

        //    for (var i = 0; i < locations.length; i++) {
        //        if (locations[i]) {
        //            var isViapoint = true;
        //            if (i == 0 || i == locations.length - 1)
        //            {
        //                isViapoint = false;
        //            }
        //            var waypoint = new Microsoft.Maps.Directions.Waypoint( {location : locations[i], isViapoint : isViapoint });
        //            directionsManager.addWaypoint(waypoint);
        //        }
        //    }
        //    directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('logisticsDirections') });
        //    directionsManager.calculateDirections();
        //}


        //
        // Push pins and display info
        //
        function pushPin() {
            var pinOrder = 0;
            for (var m in matchCord) {

                var pushpinOptions = {
                    visible: true,
                    textOffset: new Microsoft.Maps.Point(0, 10),
                    width: 37,
                    height: 48
                },
                maplink = '',
                rank = 0,
                displayRank = 0,
                displayRankNotCompleted = 0,
                pushpinType = "",
                isWarehouse = false,
                hasPickup = false,
                hasDelivery = false,
                notCompleted = false,
                icon = "/subsites/administration/content/images/pinSingle-grey.png",
                matchList = matchCord[m].list;

                for (var l in matchList) {
                    if (matchList[l].status != "Completed" && matchList[l].status != "FailedPickUp" && matchList[l].status != "FailedDelivery") {
                        notCompleted = true;
                        if (matchList[l].type == "Delivery") {
                            hasDelivery = true;
                        }
                        if (matchList[l].type == "PickUp") {
                            hasPickup = true;
                        }
                        if (matchList[l].type == "Warehouse") {
                            isWarehouse = true;
                        }
                    }
                    var packageid = matchList[l].packageId;
                    var row = $('#planning-table tr.package-' + packageid);
                    if ($("#planned-route").length) {
                        $('#planned-route .packageId').each(function () {
                            if ($(this).text() == packageid) {
                                var parentrow = $(this).closest("tr");
                                if (parentrow.find(".packageType").text() == matchList[l].type) {
                                    row = parentrow;
                                }
                            }
                        });
                        if (row.length) {
                            rank = parseInt(row.find(".packageRank").text());
                        }
                    } else {
                        if (row.length) {
                            if (matchList[l].type == "PickUp") {
                                row.find('.item-pickupaddressorder input').attr("data-pinorder", pinOrder);
                                rank = parseInt(row.find('.item-pickupaddressorder input').val());
                            } else if (matchList[l].type == "Delivery") {
                                row.find('.item-destinationaddressorder input').attr("data-pinorder", pinOrder);
                                rank = parseInt(row.find('.item-destinationaddressorder input').val());
                            }
                        }
                    }
                    
                    if (!isNaN(rank) && rank > 0) {
                        if (displayRank > rank || displayRank == 0) {
                            displayRank = rank;
                        }
                        if (matchList[l].status != "Completed" && matchList[l].status != "FailedPickUp" && matchList[l].status != "FailedDelivery") {
                            if (displayRankNotCompleted > rank || displayRankNotCompleted == 0) {
                                displayRankNotCompleted = rank;
                            }
                        }
                    }
                    pinOrder++;
                }
                if (notCompleted) {
                    displayRank = displayRankNotCompleted;
                }
                pushpinOptions.text = displayRank.toString();
                if (matchList.length > 1) {
                    // multiple items at one address
                    if (!notCompleted) {
                        icon = "/subsites/administration/content/images/pinMulti-grey.png";
                    } else if (isWarehouse) {
                        icon = "/subsites/administration/content/images/iconFlag-red.png";
                        pushpinOptions.width = 100;
                        pushpinOptions.height = 100;
                        pushpinOptions.text = "";
                    } else if (hasPickup && hasDelivery) {
                        icon = "/subsites/administration/content/images/pinMulti-green.png";
                    } else if (hasPickup) {
                        icon = "/subsites/administration/content/images/pinMulti-blue.png";
                    } else if (hasDelivery) {
                        icon = "/subsites/administration/content/images/pinMulti-orange.png";
                    } else {
                        icon = "/subsites/administration/content/images/pinMulti-grey.png";
                    }
                } else {
                    if (!notCompleted) {
                        icon = "/subsites/administration/content/images/pinSingle-grey.png";
                    } else if (isWarehouse) {
                        icon = "/subsites/administration/content/images/iconFlag-red.png";
                        pushpinOptions.width = 100;
                        pushpinOptions.height = 100;
                        pushpinOptions.text = "";
                    } else if (hasPickup && hasDelivery) {
                        icon = "/subsites/administration/content/images/pinSingle-green.png";
                    } else if (hasPickup) {
                        icon = "/subsites/administration/content/images/pinSingle-blue.png";
                    } else if (hasDelivery) {
                        icon = "/subsites/administration/content/images/pinSingle-orange.png";
                    } else {
                        icon = "/subsites/administration/content/images/pinSingle-grey.png";
                    }
                }
                
                pushpinOptions.icon = icon;
                var pushpin = new Microsoft.Maps.Pushpin(matchCord[m].loc, pushpinOptions);
                Microsoft.Maps.Events.addHandler(pushpin, 'click', displayInfo);
                map.entities.push(pushpin);
            }
            /*
            for (var i = 0; i < locationinfos.length; i++) {
                if (errorLocationIds.indexOf(i) == -1 && locationinfos[i]) {
                    var pushpinOptions = '', maplink = '', rank = '';
                    var packageid = locationinfos[i].packageId;
                    var addresstype = locationinfos[i].type;
                    var row = $('#planning-table tr.package-' + packageid);
                    if (row.length) {
                        if (locationinfos[i].type == "PickUp") {
                            row.find('.item-pickupaddressorder input').attr("data-pinorder", i);
                            rank = row.find('.item-pickupaddressorder input').val();
                        } else if (locationinfos[i].type == "Delivery") {
                            row.find('.item-destinationaddressorder input').attr("data-pinorder", i);
                            rank = row.find('.item-destinationaddressorder input').val();
                        }
                    }
                    if (locationinfos[i].status == "Completed") { 
                        pushpinOptions = { icon: "/subsites/administration/content/images/largepin-grey.png", visible: true, textOffset: new Microsoft.Maps.Point(0, 8), width: 35, height: 51, text: rank };
                        maplink = '<a href="#" class="maplink" data-index="' + i + '"><img src="/subsites/administration/content/images/pin-grey.png" /></a>';
                    } else {
                        if (addresstype == "Warehouse") {
                            pushpinOptions = { icon: "/subsites/administration/content/images/largepin-red.png", visible: true, textOffset: new Microsoft.Maps.Point(0, 8), width: 35, height: 51, text: rank };
                        } else if (addresstype == "PickUp") {
                            pushpinOptions = { icon: "/subsites/administration/content/images/largepin-blue.png", visible: true, textOffset: new Microsoft.Maps.Point(0, 8), width: 35, height: 51, text: rank };
                            maplink = '<a href="#" class="maplink" data-index="' + i + '"><img src="/subsites/administration/content/images/pin-blue.png" /></a>';
                        } else if (addresstype == "Delivery") {
                            pushpinOptions = { icon: "/subsites/administration/content/images/largepin-orange.png", visible: true, textOffset: new Microsoft.Maps.Point(0, 8), width: 35, height: 51, text: rank };
                            maplink = '<a href="#" class="maplink" data-index="' + i + '"><img src="/subsites/administration/content/images/pin-orange.png" /></a>';
                        } else {
                            pushpinOptions = { icon: "/subsites/administration/content/images/largepin-grey.png", visible: true, textOffset: new Microsoft.Maps.Point(0, 8), width: 35, height: 51, text: rank };
                        }
                    }
                    var pushpin = new Microsoft.Maps.Pushpin(locationinfos[i].geo, pushpinOptions);
                    pushpin.text = locationinfos[i].id;

                    var row = $('#planning-table tr.package-' + packageid);
                    if (row.length) {
                        if (addresstype == "PickUp") {
                            row.find('.item-pickupaddress').prepend(maplink);
                        } else if (addresstype == "Delivery") {
                            row.find('.item-destinationaddress').prepend(maplink);
                        }
                    }
                    Microsoft.Maps.Events.addHandler(pushpin, 'click', displayInfo);
                    map.entities.push(pushpin);
                }
            }
            */
            $('.maplink').click(function (e) {
                var index = $(this).attr("data-index");
                var pin = map.entities.get(index);
                map.setView({ center: pin._location, zoom: 12 });
                showInfobox(pin);
                e.stopPropagation();
                return false;
            });
            
        }

        function displayInfo(e) {
            if (e.targetType == "pushpin") {
                showInfobox(e.target);
            }
        }

        function showInfobox(shape) {
            for (var i = map.entities.getLength() - 1; i >= 0; i--) {
                var pushpin = map.entities.get(i);
                if (pushpin.toString() == '[Infobox]') {
                    map.entities.removeAt(i);
                };
            }
            var latlngString = shape._location.latitude + "_" + shape._location.longitude;
            var failedPickupTxt = "";
            var failedDeliveryTxt = "";
            var completedTxt = "";
            var txt = matchCord[latlngString].address + "</br></br>";
            for (var l in matchCord[latlngString].list) {
                var row = $('#planning-table tr.package-' + matchCord[latlngString].list[l].packageId);
                var rankD = "";
                if ($("#planned-route").length) {
                    $('#planned-route .packageId').each(function () {
                        if ($(this).text() == matchCord[latlngString].list[l].packageId) {
                            var parentrow = $(this).closest("tr");
                            if (parentrow.find(".packageType").text() == matchCord[latlngString].list[l].type) {
                                row = parentrow;
                            }
                        }
                    });
                    if (row.length) {
                        rankD = parseInt(row.find(".packageRank").text());
                    }
                } else {
                    if (row.length) {
                        if (matchCord[latlngString].list[l].type == "PickUp") {
                            rankD = parseInt(row.find('.item-pickupaddressorder input').val());
                        } else if (matchCord[latlngString].list[l].type == "Delivery") {
                            rankD = parseInt(row.find('.item-destinationaddressorder input').val());
                        }
                    }
                }
                if (isNaN(rankD) || rankD < 1) {
                    rankD = "No rank";
                }
                if (matchCord[latlngString].list[l].status == "Completed")
                {
                    completedTxt += matchCord[latlngString].list[l].packageId + "(" + matchCord[latlngString].list[l].type + "): " + rankD + "</br>";
                }
                else if (matchCord[latlngString].list[l].status == "FailedPickUp")
                {
                    failedPickupTxt += matchCord[latlngString].list[l].packageId + "(" + matchCord[latlngString].list[l].type + "): " + rankD + "</br>";
                }
                else if (matchCord[latlngString].list[l].status == "FailedDelivery")
                {
                    failedDeliveryTxt += matchCord[latlngString].list[l].packageId + "(" + matchCord[latlngString].list[l].type + "): " + rankD + "</br>";
                }
                else if ($("#planned-route").length)
                {
                    txt += matchCord[latlngString].list[l].packageId + "(" + matchCord[latlngString].list[l].type + "): " + rankD + "</br>";
                }
                else
                {
                    txt += "<span class='packageId' data-id='" + matchCord[latlngString].list[l].packageId + "' data-type='" + matchCord[latlngString].list[l].type + "'>" + matchCord[latlngString].list[l].packageId + "</span>(" + matchCord[latlngString].list[l].type + "): <span class='packageRank' data-id='" + matchCord[latlngString].list[l].packageId + "' data-type='" + matchCord[latlngString].list[l].type + "'>" + rankD + "</span></br>";
                }
            }
            txt += "</br>";
            if (failedPickupTxt != "") {
                txt += "<h4>Failed PickUp</h4>" + failedPickupTxt + "</br>";
            }
            if (failedDeliveryTxt != "") {
                txt += "<h4>Failed Delivery</h4>" + failedDeliveryTxt + "</br>";
            }
            if (completedTxt != "") {
                txt += "<h4>Completed</h4>" + completedTxt + "</br>";
            }
            var pix = map.tryLocationToPixel(shape.getLocation(), Microsoft.Maps.PixelReference.control);
            var infoboxOptions = { width: 200, height: 100, showCloseButton: true, zIndex: 99, offset: new Microsoft.Maps.Point(-110, 60), showPointer: true, htmlContent: '<div class="Infobox"><a class="infobox-close" href="#">x</a>' + txt + '</div>' };
            var defInfobox = new Microsoft.Maps.Infobox(shape.getLocation(), infoboxOptions);
            map.entities.push(defInfobox);
            $('.infobox-close').unbind("click").click(function (e) {
                for (var i = map.entities.getLength() - 1; i >= 0; i--) {
                    var pushpin = map.entities.get(i);
                    if (pushpin.toString() == '[Infobox]') {
                        map.entities.removeAt(i);
                    };
                }
                e.stopPropagation();
                return false;
            });
            $(".Infobox .packageId").unbind("click").click(function () {
                var packageId = $(this).attr("data-id");
                var packageType = $(this).attr("data-type");
                var row = $("tr.package-" + packageId);
                if (row.length) {
                    if (packageType == "PickUp") {
                        row.find(".item-pickupaddressorder input[type=text]").focus().select();
                    } else if (packageType == "Delivery") {
                        row.find(".item-destinationaddressorder input[type=text]").focus().select();
                    }
                }
            });
            $(".Infobox .packageRank").unbind("click").click(function () {
                var thisrank = parseInt($(this).text());
                if (isNaN(thisrank)) {
                    thisrank = "No Rank";
                }
                $(this).attr("data-rank", thisrank).html("<input class='changerank' type='text' value='" + $(this).text() + "' data-type='" + $(this).attr('data-type') + "' data-id='" + $(this).attr('data-id') + "' />");
                $(this).find(".changerank").focus().select();
                var _this = $(this);
                $(".changerank").unbind().blur(function () {
                    if (isNaN(parseInt($(this).val())) || $(this).val() == "") {
                        _this.text(_this.attr("data-rank"));
                    } else {
                        var rankvalue = parseInt($(this).val());
                        _this.text(rankvalue);
                        var packageId = $(this).attr("data-id");
                        var packageType = $(this).attr("data-type");
                        var row = $("tr.package-" + packageId);
                        if (row.length) {
                            if (packageType == "PickUp") {
                                row.find(".item-pickupaddressorder input[type=text]").val(rankvalue);
                            } else if (packageType == "Delivery") {
                                row.find(".item-destinationaddressorder input[type=text]").val(rankvalue);
                            }
                        }
                        var rank = 0, displayRank = 0, displayRankNotCompleted = 0, notCompleted = false;
                        for (var m in matchCord) {
                            for (var li in matchCord[m].list) {
                                if (matchCord[m].list[li].packageId == packageId && matchCord[m].list[li].type == packageType) {
                                    cord = m;
                                    matchList = matchCord[m].list;
                                    
                                    for (var l in matchList) {
                                        if (matchList[l].status != "Completed" && matchList[l].status != "FailedPickUp" && matchList[l].status != "FailedDelivery") {
                                            notCompleted = true;
                                        }
                                        if (row.length) {
                                            if (matchList[l].type == "PickUp") {
                                                rank = parseInt(row.find('.item-pickupaddressorder input').val());
                                            } else if (matchList[l].type == "Delivery") {
                                                rank = parseInt(row.find('.item-destinationaddressorder input').val());
                                            }
                                        }
                                        if (!isNaN(rank) && rank > 0) {
                                            if (displayRank > rank || displayRank == 0) {
                                                displayRank = rank;
                                            }
                                            if (matchList[l].status != "Completed" && matchList[l].status != "FailedPickUp" && matchList[l].status != "FailedDelivery") {
                                                if (displayRankNotCompleted > rank || displayRankNotCompleted == 0) {
                                                    displayRankNotCompleted = rank;
                                                }
                                            }
                                        }
                                    }
                                    if (notCompleted) {
                                        displayRank = displayRankNotCompleted;
                                    }
                                }
                            }
                        }
                        for (var i = map.entities.getLength() - 1; i >= 0; i--) {
                            var pushpin = map.entities.get(i);
                            if (pushpin.toString() == '[Pushpin]' && pushpin._location.latitude + "_" + pushpin._location.longitude == cord) {
                                if ($(this).val() == "") {
                                    pushpin._text = "";
                                } else {
                                    pushpin._text = displayRank.toString();
                                }
                                map.entities.removeAt(i);
                                map.entities.insert(pushpin, i);
                            };
                        }
                    }
                }).keypress(function (e) {
                    if (event.keyCode == 13) {
                        $(this).trigger("blur");
                    }
                });
            });
            /*
            var txt, packageid, rank, links = '';
            for (var j = 0; j < locationinfos.length; j++) {
                if (errorLocationIds.indexOf(j) == -1 && locationinfos[j].id == shape.text) {
                    txt = locationinfos[j].address + "<br />" + locationinfos[j].type + "<br />";
                    packageid = locationinfos[j].packageId;
                    var row = $('#planning-table tr.package-' + packageid);
                    if (row.length) {
                        if (locationinfos[j].type == "PickUp") {
                            rank = row.find('.item-pickupaddressorder input').val();
                        } else if (locationinfos[j].type == "Delivery") {
                            rank = row.find('.item-destinationaddressorder input').val();
                        }
                    }
                    if (locationinfos[j].type == "Delivery") {
                        links = '<form><a class="locationfocus" data-addresstype="delivery" data-packageid="' + packageid + '" href="#">Delivery Order:</a> <a class="locationorder" data-addresstype="delivery" data-packageid="' + packageid + '" href="#">' + rank + '</a> <input class="locationinput" data-addresstype="delivery" data-packageid="' + packageid + '" type="text" value="' + rank + '" /> <button class="locationconfirm" data-addresstype="delivery" data-packageid="' + packageid + '">Ok</button></form>';
                    } else if (locationinfos[j].type == "PickUp") {
                        links = '<form><a data-packageid="' + packageid + '" href="#" class="locationfocus" data-addresstype="pickup">Pickup Order:</a> <a data-packageid="' + packageid + '" href="#" class="locationorder" data-addresstype="pickup">' + rank + '</a> <input class="locationinput" data-addresstype="pickup" data-packageid="' + packageid + '" type="text" value="' + rank + '"> <input type="button" class="locationconfirm" data-addresstype="pickup" data-packageid="' + packageid + '" value="Ok" /></form>';
                    }
                }
            }
            var pix = map.tryLocationToPixel(shape.getLocation(), Microsoft.Maps.PixelReference.control);
            var infoboxOptions = { width: 200, height: 100, showCloseButton: true, zIndex: 99, offset: new Microsoft.Maps.Point(-110, 60), showPointer: true, htmlContent: '<div class="Infobox"><a class="infobox-close" href="#">x</a>' + txt + '<br />' + links + '</div>' };
            var defInfobox = new Microsoft.Maps.Infobox(shape.getLocation(), infoboxOptions);
            map.entities.push(defInfobox);
            $('.locationconfirm, .locationinput').hide();
            $('.locationfocus').click(function (e) {
                var packageid = $(this).attr("data-packageid");
                var addresstype = $(this).attr("data-addresstype");
                var row = $('#planning-table tr.package-' + packageid);
                if (row.length) {
                    if (addresstype == "pickup") {
                        row.find('.item-pickupaddressorder input').focus();
                    } else if (addresstype == "delivery") {
                        row.find('.item-destinationaddressorder input').focus();
                    }
                }
                e.stopPropagation();
                return false;
            });
            $('.locationinput').click(function () {
                $(this).focus();
            }).blur(function(){
                value = $(this).val();
                var packageid = $(this).attr("data-packageid");
                var addresstype = $(this).attr("data-addresstype");
                var row = $('#planning-table tr.package-' + packageid);
                if (row.length) {
                    if (addresstype == "pickup") {
                        row.find('.item-pickupaddressorder input').val(value).trigger('blur');
                    } else if (addresstype == "delivery") {
                        row.find('.item-destinationaddressorder input').val(value).trigger('blur');
                    }
                }
                $(this).parent().find('.locationorder').text(value).show();
                $(this).parent().find('.locationconfirm, .locationinput').hide();
            });
            $('.locationconfirm').click(function (e) {
                value = $(this).prev('.locationinput').val();
                var packageid = $(this).attr("data-packageid");
                var addresstype = $(this).attr("data-addresstype");
                var row = $('#planning-table tr.package-' + packageid);
                if (row.length) {
                    if (addresstype == "pickup") {
                        row.find('.item-pickupaddressorder input').val(value).trigger('blur');
                    } else if (addresstype == "delivery") {
                        row.find('.item-destinationaddressorder input').val(value).trigger('blur');
                    }
                }
                $(this).parent().find('.locationorder').text(value).show();
                $(this).parent().find('.locationconfirm, .locationinput').hide();
                e.stopPropagation();
                return false;
            });
            $('.locationorder').click(function (e) {
                $(this).parent().find('.locationconfirm, .locationinput').show();
                $(this).parent().find('.locationinput').focus();
                $(this).hide();
                e.stopPropagation();
                return false;
            });
            
            */
        }
        
        $('.item-pickupaddressorder input, .item-destinationaddressorder input').focus(function () {
            $(this).attr("data-value", $(this).val());
        });

        $('.item-pickupaddressorder input, .item-destinationaddressorder input').blur(function () {
            for (var i = map.entities.getLength() - 1; i >= 0; i--) {
                var pushpin = map.entities.get(i);
                if (pushpin.toString() == '[Infobox]') {
                    map.entities.removeAt(i);
                };
            }
            if ((!isNaN(parseInt($(this).val())) || $(this).val() == "") && parseInt($(this).val()) != $(this).attr("data-value")) {
                var packageId = $(this).attr("data-id");
                var packageType = $(this).attr("data-type");
                var cord = "";
                var rank = 0, displayRank = 0, displayRankNotCompleted = 0, notCompleted = false;
                for (var m in matchCord) {
                    for (var li in matchCord[m].list) {
                        if (matchCord[m].list[li].packageId == packageId && matchCord[m].list[li].type == packageType) {
                            cord = m;
                            matchList = matchCord[m].list;

                            for (var l in matchList) {
                                var packageid = matchList[l].packageId;
                                if (matchList[l].status != "Completed" && matchList[l].status != "FailedPickUp" && matchList[l].status != "FailedDelivery") {
                                    notCompleted = true;
                                }
                                var row = $('#planning-table tr.package-' + packageid);
                                if (row.length) {
                                    if (matchList[l].type == "PickUp") {
                                        rank = parseInt(row.find('.item-pickupaddressorder input').val());
                                    } else if (matchList[l].type == "Delivery") {
                                        rank = parseInt(row.find('.item-destinationaddressorder input').val());
                                    }
                                }
                                if (!isNaN(rank) && rank > 0) {
                                    if (displayRank > rank || displayRank == 0) {
                                        displayRank = rank;
                                    }
                                    if (matchList[l].status != "Completed" && matchList[l].status != "FailedPickUp" && matchList[l].status != "FailedDelivery") {
                                        if (displayRankNotCompleted > rank || displayRankNotCompleted == 0) {
                                            displayRankNotCompleted = rank;
                                        }
                                    }
                                }
                            }
                            if (notCompleted) {
                                displayRank = displayRankNotCompleted;
                            }
                        }
                    }
                }
                if (cord != "") {
                    for (var i = map.entities.getLength() - 1; i >= 0; i--) {
                        var pushpin = map.entities.get(i);
                        if (pushpin.toString() == '[Pushpin]' && pushpin._location.latitude + "_" + pushpin._location.longitude == cord) {
                            if ($(this).val() == "") {
                                pushpin._text = "";
                            } else {
                                pushpin._text = displayRank.toString();
                            }
                            map.entities.removeAt(i);
                            map.entities.insert(pushpin, i);
                        };
                    }
                }

            } else {
                var inputValue = parseInt($(this).attr("data-value"));
                if (isNaN(inputValue)) {
                    inputValue = "";
                }
                $(this).val(inputValue);
            }
        });

        $('#autosort').click(function () {
            autosort();
        });

        $('#restore').click(function () {
            restoresort();
        });

        function autosort() {
            var sortarray = [];
            var i = 0;
            $('#planning-table input[type="text"]').each(function () {
                if ($(this).val() != '') {
                    sortarray.push({ key: i, value: $(this).val() });
                    $(this).attr("data-customorder", i);
                    i++;
                }
            });

            var output = '';
            for (var l = 0; l < sortarray.length; l++){
                output += l+ ', ' + sortarray[l].key + ', ' + sortarray[l].value + '; ';
            }     

            sortarray.sort(function (a, b) {
                if (parseInt(a.value) < parseInt(b.value)) {
                    return -1;
                } else if (parseInt(a.value) > parseInt(b.value)) {
                    return 1;
                } else {
                    return 0;
                }
            });

            var ordervalue = 0;
            var prevvalue = 0;
            var startvalue = 0;
            var step = 50;
            $(".donePackageOrder").each(function () {
                var doneOrder = parseInt($(this).text());
                if (!isNaN(doneOrder) && doneOrder >= startvalue) {
                    startvalue = doneOrder;
                }
            });
            for (var j = 0; j < sortarray.length; j++) {
                if (j == 0) {
                    if (!$(".donePackageOrder").length) {
                        ordervalue = step;
                    } else {
                        ordervalue = startvalue + step;
                    }
                } else {
                    ordervalue += step;
                }
                prevvalue = sortarray[j].value;
                sortarray[j].value = ordervalue;
                $('#planning-table input[data-customorder=' + sortarray[j].key + ']').val(sortarray[j].value);
            }
            globalmaxorder = ordervalue;
            $('.item-pickupaddressorder input, .item-destinationaddressorder input').trigger("blur");
        }

        function restoresort() {
            $('#planning-table input[type="text"]').each(function () {
                $(this).val('');
            });
            for (var b = 0; b < defaultarray.length; b++) {
                $('#planning-table input[data-defaultorder=' + defaultarray[b].key + ']').val(defaultarray[b].value);
            }
            $('.item-pickupaddressorder input, .item-destinationaddressorder input').trigger("blur");
        }

    </script>
    <div id="mapErrors"></div>
    <div id="logisticsMap" style="position: relative; width: 100%; height: 700px;"></div>
    <div id='logisticsDirections'></div>
</div>

